package com.example.paging3samples.network

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.paging3samples.network.model.konachan.KoNaChan
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class PagingSampleRepo @Inject constructor(private val apiService: ApiService) {

    suspend fun getCategories(liveData: MutableLiveData<CustomResult<PageResult>>, query: String) {
        liveData.value = CustomResult.Loading(true)
        try {
            val categories = apiService.getCategories(1)
            Log.i("result categories:", categories.toString())
            liveData.value = CustomResult.Success(categories)
        } catch (e: Exception) {
            Log.e("onFailure", e.message.toString())
            if (e.message != null && e.message?.isNotEmpty() == true) {
                liveData.value =
                    CustomResult.Error.RecoverableError(Exception(e.message.toString()))
            } else {
                liveData.value = CustomResult.Error.NonRecoverableError(Exception("Un-traceable"))
            }
        }
    }

    suspend fun getKoNaChanPost(): Flow<List<KoNaChan>> {
        val koNaChanList = apiService.getKoNaChanList()
        koNaChanList.map {
            it.forEach {
                print(it)
            }
        }
        return koNaChanList
    }

}